<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
<form action="http://xxx.com/register" id="registerForm" method="post">
  请输入用户名： <input type="text" name="userName"/>
  请输入密码： <input type="text" name="password">
  请输入手机号码：<input type="text" name="phoneNumber"/>
  <button>提交</button>
</form>
<script>
  // 表单校验例子(版本1)
  // var registerForm = document.querySelector('#registerForm');
  // registerForm.onsubmit = function () {
  //   if (registerForm.userName.value === '') {
  //     alert('用户名不能为空')
  //     return false
  //   }
  //   if (registerForm.password.value.length < 6) {
  //     alert("密码长度不能少于6位")
  //     return false;
  //   }
  //   if (!/^1[3|5|8][0-9]{9}$/.test(registerForm.phoneNumber.value)) {
  //     alert("手机号码格式不正确")
  //     return false;
  //   }
  // }


  // 表单校验例子(版本2)
  var strategies = {
    isNonEmpty: function (value, errorMsg) {
      if (value === '') {
        return errorMsg
      }
    },
    minLength: function (value, length, errorMsg) {
      if (value.length < length) {
        return errorMsg
      }
    },
    isMobile: function (value, errorMsg) {
      if (!/^1[3|5|8][0-9]{9}$/.test(value)) {
        return errorMsg
      }
    }
  }

  var validateFunc = function (value, length, errorMsg) {
    var validator = new Validator()
    var registerForm = document.querySelector("#registerForm")

    validator.add(registerForm.userName, 'isNonEmpty', '用户名不能为空')
    validator.add(registerForm.password, 'minLength:6', '密码长度不能少于6位')
    validator.add(registerForm.phoneNumber, 'isMobile', "请输入正确手机号")

    validator.start()
  }
  var Validator = function () {
    this.cache = []
  }

  Validator.prototype.add = function (dom, rule, errorMsg) {
    var arr = rule.split(':')
    this.cache.push(function () {
      var strategy = arr.shift();
      arr.unshift(dom.value)
      arr.push(errorMsg)
      return strategies[strategy].apply(dom, arr)
    })
  }

  Validator.prototype.start = function () {
    for (let i = 0, l = this.cache.length; i < l; i++) {
      var error = validateFunc()
      if (error) {
        return error
      }
    }
  }


  validator.add(registerForm.userName, [
    {
      strategy: 'isNonEmpty',
      errorMsg: '用户名不能为空'
    },
    {
      strategy: 'minLength:6',
      errorMsg: '用户名长度不能小于10位'
    }
  ])


</script>
</body>
</html>
